﻿function ProfileMenuItemControl(model) {
    var self = this;

    self.IsHtmlLoaded = false;

    self.AjaxLoader = new AjaxLoader();

    self.params = {};

    self.panelName = model.panelName;
    self.buttonSelector = "#" + model.panelName;
    self.tabContainerSelector = self.buttonSelector + "-tab";
    self.topBarName = model.panelName + "-top-bar";
    self.bottomBarName = model.panelName + "-bottom-bar";
    self.htmlUrl = model.htmlUrl,
    self.dataUrl = model.dataUrl;
    self.templateSelector = "#" + model.panelName + "-template";
    self.templateContentSelector = "#" + model.panelName + "-tab-content";

    $(self.buttonSelector).click(function () {
        self.Reload();
    });

    self.Reload = function() {

        var d1 = new $.Deferred();

        if (!self.IsHtmlLoaded) {
            self.AjaxLoader.SetLoad(self.tabContainerSelector);
            $.ajax({
                url: self.htmlUrl,
                type: 'GET',
                dataType: 'html',
                success: function(data) {

                    self.IsHtmlLoaded = true;

                    $(self.tabContainerSelector).html(data);

                    self.MessageBarControl = new MessagesBarControl(self.panelName);

                    self.NavigationTopBarControl = new NavigationBarControl(self.topBarName, self.GetData);

                    self.NavigationBottomBarControl = new NavigationBarControl(self.bottomBarName, self.GetData);

                    d1.resolve();
                }
            });
        } else {
            d1.resolve();
        }

        $.when(d1).done(function() {
            self.GetData(self.params);
        });
    };

    self.GetData = function (params) {
        var page = 1;
        $.ajax({
            url: self.dataUrl,
            type: 'GET',
            data: { page : page },
            dataType: 'json',
            success: function (data) {
                var template = $(self.templateSelector).html();
                Mustache.parse(template);
                var result = Mustache.render(template, { RootTag: data });
                $(self.templateContentSelector).html(result);
            }
        });
    }
}